import { _decorator, Color, Component, Label, Node, RichText, Sprite, v3, Vec2, Vec3 } from 'cc';
import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';
import { UserInfo } from '../common/UserInfo';
import { Utils } from '../common/Utils';
import { Building, EventOper } from '../entity/Buildings';
import { BuildingBtnCheck, CheckResult } from './BuildingBtnCheck';
import { VillageController } from './VillageController';
import { Space } from './Space';
import { SpaceBtnConfig, SpaceBtnType } from './SpaceBtn';
import { EventManager } from '../event/EventManager';
import { BManager } from '../entity/BManager';
import { buildingType, EventType } from '../settings/const';
import VillageApi from '../api/VillageApi';
import { AudioManager, Mp3Enum } from '../common/AudioManager';
const { ccclass, property } = _decorator;

@ccclass('BuildingUpGrade')
export class BuildingUpGrade extends Component {
    @property(Node)
    mask: Node
    @property(Node)
    public closeBtn: Node;
    @property(Sprite)
    public cover: Sprite;
    @property(Label)
    public buildName: Label;
    @property(Label)
    countTime: Label
    @property(Label)
    public level: Label;
    @property(Label)
    public desc: Label;
    @property(Label)
    public food: Label;
    @property(Label)
    public iron: Label;
    @property(Label)
    public mud: Label;
    @property(Label)
    public wood: Label;
    @property(Label)
    public time: Label;
    @property(Label)
    public curIncrease: Label
    @property(Label)
    public nextIncrease: Label
    @property(Label)
    public nextLevelRes: Label
    @property(Label)
    public curIncreaseTitle: Label
    @property(Label)
    public nextIncreaseTitle: Label
    @property(Node)
    resDiv:Node
    @property(Node)
    timeDiv:Node
    @property(Node)
    public btnLayout: Node
    @property(Node)
    public remove: Node;
    @property(Node)
    public develop: Node;
    @property(Node)
    public upGrade: Node;
    @property(Node)
    public army: Node
    @property(Node)
    public transport: Node
    @property(Node)
    public train: Node
    @property(Node)
    public palace: Node
    @property(Node)
    public union: Node
    @property(Node)
    public cancel: Node
    @property(Node)
    public speed: Node
    @property(Node)
    public trea: Node
    @property(Node)
    public heroYard: Node

    /**当前等级的数据 */
    private curData: Building;
    /**下一级的数据 */
    private nextData: Building;

    offTime: number = 0

    start() {
        this.mask.on(Node.EventType.TOUCH_END, this.onClose, this)
        this.closeBtn.on(Node.EventType.TOUCH_END, this.onClose, this)
        this.remove.on(Node.EventType.TOUCH_END, this.onRemove, this)
        this.develop.on(Node.EventType.TOUCH_END, this.onDevelop, this)
        this.upGrade.on(Node.EventType.TOUCH_END, this.onUpGrade, this)

        this.army.on(Node.EventType.TOUCH_END, this.onArmy, this)
        this.transport.on(Node.EventType.TOUCH_END, this.onTransport, this)
        this.train.on(Node.EventType.TOUCH_END, this.onTrain, this)
        this.palace.on(Node.EventType.TOUCH_END, this.onPalace, this)
        this.union.on(Node.EventType.TOUCH_END, this.onUnion, this)

        this.cancel.on(Node.EventType.TOUCH_END, this.onCancel, this)
        this.speed.on(Node.EventType.TOUCH_END, this.onSpeed, this)
        this.trea.on(Node.EventType.TOUCH_END, this.onTrea, this)
        this.heroYard.on(Node.EventType.TOUCH_END, this.onHeroYard, this)

    }

    // 设置数据，并渲染UI
    public async setData(data: Building) {
        console.log(data)
        this.curData = data
        // 判断建筑物是否满级
        if (this.curData.level < this.curData.maxLevel) {
            //未满级
            this.nextData = Building.createByIdAndLevel(data.id, data.level + 1)
        } else {
            // 已经满级
            this.nextData = this.curData

        }

        console.log(this.nextData)


        this.buildName.string = data.name
        this.level.string = data.level + ''
        this.desc.string = data.desc

        this.food.string = Utils.bigNumberTransform(this.nextData.food)
        this.wood.string = Utils.bigNumberTransform(this.nextData.wood)
        this.mud.string = Utils.bigNumberTransform(this.nextData.mud)
        this.iron.string = Utils.bigNumberTransform(this.nextData.iron)

        this.cover.spriteFrame = await data.getImg()
        Building.setCoverSize(this.cover.node.parent, this.cover)

        let wood_reserve = UserInfo.instance.villageData.res.wood_reserve
        let mud_reserve = UserInfo.instance.villageData.res.mud_reserve
        let iron_reserve = UserInfo.instance.villageData.res.iron_reserve
        let food_reserve = UserInfo.instance.villageData.res.food_reserve


        if (wood_reserve < this.nextData.wood) {
            this.wood.color = new Color('#FD4545')
        }
        if (mud_reserve < this.nextData.mud) {
            this.mud.color = new Color('#FD4545')
        }
        if (iron_reserve < this.nextData.iron) {
            this.iron.color = new Color('#FD4545')
        }
        if (food_reserve < this.nextData.food) {
            this.food.color = new Color('#FD4545')
        }



        this.time.string = Utils.secondToStr(this.nextData.time / UserInfo.instance.speed)
        this.curIncreaseTitle.string = data.increaseNum.title
        this.curIncrease.string = data.increaseNum.num
        this.nextIncreaseTitle.string = this.nextData.increaseNum.levelTitle
        this.nextIncrease.string = this.nextData.increaseNum.num

        this.nextLevelRes.string = `升到${this.nextData.level}级的成本`

        if (this.curData.level >= this.curData.maxLevel) {
            this.nextIncrease.node.active = false
            this.nextIncreaseTitle.node.active = false
            
            this.resDiv.active = false
            this.timeDiv.active = false
        }



        this.setBtnShow()


        this.setEvent()

    }

    setEvent() {
        let event = this.curData.getBuildingEvent()
        if (!event) {
            this.countTime.node.active = false
            return
        }

        let eStartTime = event.eStartTime
        this.offTime = eStartTime - Math.floor(UserInfo.instance.serverTime / 1000)
        if (this.offTime <= 0) {
            return
        }

        if (event.eType == EventType.advBuild) {

        }

        this.countTime.string = event.title + '：' + Utils.secondToStr(this.offTime)
        this.schedule(this.updateTime, 1, this.offTime - 1)

    }

    updateTime() {
        let event = this.curData.getBuildingEvent()
        if (!event) {
            this.unschedule(this.updateTime)
            return
        }

        this.offTime--
        this.countTime.string = event.title + '：' + Utils.secondToStr(this.offTime)

        if (this.offTime <= 0) {
            // 倒计时完成
            // 清除事件，刷新页面
            UserInfo.instance.refreshVillageDetail()
            let bm = BManager.getBManage(this.curData.uid)
            let bu = Building.createBuildingByBManager(bm)
            this.setData(bu)
        }
    }
    // 设置底下的按钮的显示
    setBtnShow() {
        for (let ch of this.btnLayout.children) {
            ch.position = v3(-600, 0, 0)
        }

        let config = SpaceBtnConfig[this.curData.id]
        let btnList: Node[] = []
        for (let item of config) {
            switch (item) {
                case SpaceBtnType.Remove:

                    if (!this.curData.isBuilding && !this.curData.isRemoving) {
                        btnList.push(this.remove)
                    }
                    break
                case SpaceBtnType.Develop:
                    btnList.push(this.develop)
                    break
                case SpaceBtnType.Army:
                    btnList.push(this.army)
                    break
                case SpaceBtnType.Transport:
                    btnList.push(this.transport)
                    break
                case SpaceBtnType.Train:
                    btnList.push(this.train)
                    break
                case SpaceBtnType.Expand:
                    btnList.push(this.palace)
                    break
                case SpaceBtnType.Union:
                    btnList.push(this.union)
                    break
                case SpaceBtnType.Trea:
                    btnList.push(this.trea)
                    break
                case SpaceBtnType.HeroYard:
                    btnList.push(this.heroYard)
                    break
                case SpaceBtnType.UpGrade:
                    if (!this.curData.isBuilding && !this.curData.isRemoving) {
                        btnList.push(this.upGrade)
                    }

                    break
            }
        }

        // 如果是正在建造或者拆除
        if (this.curData.isBuilding || this.curData.isRemoving) {
            btnList.unshift(this.speed)
            btnList.unshift(this.cancel)
        }

        // 如果是拆除，给加速按钮上添加一个元宝的图标
        if (this.curData.isRemoving) {
            this.speed.getChildByName('gold').active = true
        } else {
            this.speed.getChildByName('gold').active = false
        }

        // 如果是大小宫殿，就删除加速按钮
        if (this.curData.id == buildingType.B25_Residence || this.curData.id == buildingType.B26_Palace) {
            for (let i = btnList.length - 1; i >= 0; i--) {
                if (btnList[i] == this.speed) {
                    btnList.splice(i, 1)
                }
            }
        }

        let num = Math.floor(btnList.length / 2)
        let isEven = btnList.length % 2 == 0
        let list: Vec3[] = []
        if (!isEven) {
            list.push(v3(0, 0, 0))
        }
        for (let i = 0; i < num; i++) {
            let index = i + 1
            list.unshift(v3(-150 * index, 0, 0))
            list.push(v3(150 * index, 0, 0))
        }

        for (let i = 0; i < list.length; i++) {
            btnList[i].position = list[i]

        }


    }

    onClose() {
        UIManager.instance.closeUI(PrefabEnum.BuildingUpGrade)
        // UIManager.instance.closeUI(PrefabEnum.BuildingList)
    }

    onRemove() {
        let result = BuildingBtnCheck.chekcRemoveBtn(this.curData)
        if (result == CheckResult.NoRemoveWorker) {
            UIManager.instance.openUI(PrefabEnum.WorkerList)
        }
        if (result != CheckResult.Pass) {
            return
        }
        let spaceList = VillageController.instance.spaceList
        for (let ch of spaceList.children) {
            let space = ch.getComponent(Space)
            if (space.buildData.uid == this.curData.uid) {
                space.onRemove()
            }

        }

        EventManager.instance.emit(EventManager.EventType.RemoveWall, this.curData.uid)

        this.onClose()
    }

    onDevelop() {
        UIManager.instance.openUI(PrefabEnum.DevelopIndex)
    }

    onUpGrade() {
        if (!this.curData.isEnoughConsumeForBuild) {
            UIManager.instance.modal('提示', '粮食产量不足，请先升级农田', false)
            return
        }


        let result = BuildingBtnCheck.checkUpGrdeBtn(this.curData)
        if (result == CheckResult.NoWorker) {
            UIManager.instance.openUI(PrefabEnum.WorkerList)
        }
        if (result != CheckResult.Pass) {
            return
        }



        EventManager.instance.emit(EventManager.EventType.BuildWall, this.curData.uid)



        let spaceList = VillageController.instance.spaceList
        for (let ch of spaceList.children) {
            let space = ch.getComponent(Space)
            if (space.buildData.uid == this.curData.uid) {
                space.buildBuilding(this.curData.id)
            }

        }


        UIManager.instance.clear()

    }

    async onCancel() {
        await UIManager.instance.showLoading()
        let res = await VillageApi.eventOper({
            ac: EventOper.CANCEL,
            eid: this.curData.getBuildingEvent().eHandle
        })
        UIManager.instance.closeLoading()
        console.log(`取消，事件句柄${this.curData.getBuildingEvent().eHandle}:`, res)
        await UserInfo.instance.refreshVillageDetail()
        UIManager.instance.tip('已取消')
        this.onClose()
        // let bm = BManager.getBManage(this.curData.uid)
        // let bu = Building.createBuildingByBManager(bm)
        // this.setData(bu)
    }

    async onSpeed() {
        // let result = BuildingBtnCheck.checkSpeedBtn(this.curData)
        // if (result != CheckResult.Pass) {
        //     UIManager.instance.tip(result)
        //     return
        // }

        let param = {
            ac: EventOper.CANCEL,
            eid: this.curData.getBuildingEvent().eHandle
        }
        if (this.curData.isBuilding) {
            param.ac = EventOper.SPEED_BUILD
            AudioManager.instance.playOneShot(Mp3Enum.construction_complete)
        }
        if (this.curData.isRemoving) {
            param.ac = EventOper.SPEED_REMOVE
            AudioManager.instance.playOneShot(Mp3Enum.construction_downgrade)
        }
        await UIManager.instance.showLoading()
        let res = await VillageApi.eventOper(param)
        UIManager.instance.closeLoading()
        console.log(`速拆与速建ac =${param.ac} ,del =${param.eid} `, res)

        await UserInfo.instance.refreshVillageDetail()
        UIManager.instance.tip('已加速')
        this.onClose()

        // let bm = BManager.getBManage(this.curData.uid)
        // let bu = Building.createBuildingByBManager(bm)
        // this.setData(bu)
    }

    onArmy() {
        UIManager.instance.openUI(PrefabEnum.ArmyIndex)

    }
    onTransport() {
        if (UserInfo.instance.villageData.villageObjList.length == 1) {
            UIManager.instance.modal('提示', `您只有一个村庄，没有可运往的村庄。`, false)
            return
        }
        UIManager.instance.openUI(PrefabEnum.Transport)

    }
    onTrain() {
        UIManager.instance.openUI(PrefabEnum.TrainIndex)

    }

    onPalace() {
        UIManager.instance.openUI(PrefabEnum.PalaceIndex)

    }

    onUnion() {
        UIManager.instance.openUI(PrefabEnum.AllyIndex)

    }

    onTrea() {
        UIManager.instance.openUI(PrefabEnum.Trea)
    }
    onHeroYard() {
        UIManager.instance.openUI(PrefabEnum.HeroYard)
    }

}


